package org.zoomdev.zoom.validator.impl;

import org.zoomdev.zoom.validator.Validator;
import org.zoomdev.zoom.validator.annotations.RegexpFormat;

import java.util.regex.Pattern;

public class RegexpValidator implements Validator {
    private final Pattern pattern;
    private final String message;

    public RegexpValidator(RegexpFormat regexp) {
        this.pattern = Pattern.compile(regexp.value());
        this.message = regexp.message();
    }

    public RegexpValidator(org.zoomdev.zoom.validator.annotations.Pattern regexp) {
        this.pattern = Pattern.compile(regexp.regexp());
        this.message = regexp.message();
    }

    @Override
    public boolean isValid(Object value) {
        if (!(value instanceof CharSequence)) return true;
        return pattern.matcher((CharSequence) value).matches();
    }

    @Override
    public String getMessage() {
        return message;
    }
}